# ------------------------------------------------------------------------------
# Face Detection Detector
# ------------------------------------------------------------------------------
# 使用 Haar Cascade 进行人脸检测
# ------------------------------------------------------------------------------

import cv2
import os
from .base_detector import BaseDetector


class FaceDetector(BaseDetector):
    """人脸检测器"""
    
    def __init__(self):
        super().__init__()
        # 加载 Haar Cascade 分类器
        cascade_path = os.path.join(
            os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
            'face-detection',
            'haarcascade_frontalface_default.xml'
        )
        
        # 如果找不到，尝试使用 OpenCV 自带的
        if not os.path.exists(cascade_path):
            cascade_path = cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
            
        self.face_cascade = cv2.CascadeClassifier(cascade_path)
        
        if self.face_cascade.empty():
            raise Exception("无法加载人脸检测模型")
            
    def process_frame(self, frame):
        """
        检测人脸并在图像上标注
        
        Args:
            frame: 输入图像帧
            
        Returns:
            frame: 标注了人脸的图像帧
        """
        self.update_fps()
        
        # 转换为灰度图
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        
        # 检测人脸
        faces = self.face_cascade.detectMultiScale(gray, 1.1, 4)
        
        # 绘制人脸矩形框
        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
            # 添加标签
            cv2.putText(frame, '人脸', (x, y-10), 
                       cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2)
        
        # 显示检测到的人脸数量
        face_count_text = f'检测到 {len(faces)} 张人脸'
        cv2.putText(frame, face_count_text, (24, 50), 
                   cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0), 1)
        
        frame = self.visualize_fps(frame)
        return frame

